package com.lagou;

import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.RabbitListenerContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import java.net.URI;

@Configuration
@ComponentScan("com.lagou")
@EnableRabbit
public class SpringConfig {
    /**
     * 连接工厂
     */
    @Bean
    public ConnectionFactory connectionFactory() {
        return new CachingConnectionFactory(URI.create("amqp://guest:guest@localhost:5672/%2f"));
    }

    /**
     * RabbitTemplate：消息发送接收的主类
     */
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        return new RabbitTemplate(connectionFactory);
    }

    /**
     * 自动声明交换器，队列及绑定
     */
    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
        return new RabbitAdmin(connectionFactory);
    }

    /**
     * 定义队列
     */
    @Bean
    public Queue queue() {
        return new Queue("MyQueue", true, false, true, null);
    }

    /**
     * rabbitListenerContainerFactory：必须提供
     */
    @Bean
    public RabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory simpleRabbitListenerContainerFactory = new SimpleRabbitListenerContainerFactory();
        /**
         * 设置连接工厂
         */
        simpleRabbitListenerContainerFactory.setConnectionFactory(connectionFactory);
        /**
         * 并发的接收推送消息并设置并发数
         */
        simpleRabbitListenerContainerFactory.setConcurrentConsumers(5);
        return simpleRabbitListenerContainerFactory;
    }
}
